package main

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"
)

// 图片转webp工具
func main() {
	checkCwebpCmd()
	var projectPath string
	var isReplace bool
	flag.StringVar(&projectPath, "path", ".", "项目路径")
	flag.BoolVar(&isReplace, "isReplace", false, "是否替换源文件")
	flag.Parse()

	readDir(projectPath, isReplace)
}

// 读取目录
func readDir(path string, isReplace bool) {
	if infos, e := ioutil.ReadDir(path); e == nil {
		for _, temp := range infos {
			dir := temp.IsDir()
			name := temp.Name()
			if dir && !strings.Contains(name, "assets") {
				readDir(path+"/"+name, isReplace)
			} else if strings.HasSuffix(name, ".JPG") || strings.HasSuffix(name, ".JPEG") ||
				strings.HasSuffix(name, ".jpg") || strings.HasSuffix(name, ".jpeg") ||
				strings.HasSuffix(name, ".png") || strings.HasSuffix(name, ".PNG") {
				split := strings.Split(name, ".")
				dispFile(path+"/"+name, path, split[0])
				if isReplace {
					if err := os.Remove(path + "/" + name); err != nil {
						panic(err)
					}
				}
			}
		}
	}
}

// 处理文件
func dispFile(path, dirPath, name string) {
	var parms = []string{
		"-o",
		dirPath + "/" + name + ".webp",
		path,
	}
	if _, err := execCmd("cwebp", parms); err != nil {
		panic(err)
	}
}

func execCmd(shell string, raw []string) (int, error) {
	fmt.Println(shell, raw)
	cmd := exec.Command(shell, raw...)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println(err)
		return 0, nil
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Println(err)
		return 0, nil
	}
	if err := cmd.Start(); err != nil {
		fmt.Println(err)
		return 0, nil
	}
	s := bufio.NewScanner(io.MultiReader(stdout, stderr))

	for s.Scan() {
		text := s.Text()
		fmt.Println(text)
	}
	if err := cmd.Wait(); err != nil {
		fmt.Println(err)
	}
	return 0, nil
}

func shellout(command string) (error, string, string) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd := exec.Command("bash", "-c", command)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	return err, stdout.String(), stderr.String()
}

func checkCwebpCmd() {
	err, _, _ := shellout("which cwebp")
	if err != nil {
		log.Printf("not found cwebp, error: %v\n", err)
		os.Exit(1)
	}
}
